package com.studentachievement.servlets;

import javax.servlet.http.*;

import com.studentachievement.beans.Admin;
import com.studentachievement.beans.Course;
import com.studentachievement.beans.Score;
import com.studentachievement.beans.Student;
import com.studentachievement.dao.AdminDAO;
import com.studentachievement.dao.StudentDAO;
import com.studentachievement.utils.DatabaseUtil;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.Date;
import java.util.List;

@WebServlet("/AdminHomeServlet")
public class AdminHomeServlet extends HttpServlet {
    static public HttpSession sessionOk;

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response){
        // 设置响应内容类型
        response.setContentType("text/html;charset=UTF-8");
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String notok = null;
        HttpSession sessionNotOk = request.getSession();
        //从会话中获取登录者信息
        HttpSession session = request.getSession(false); // false 表示如果没有session则返回null
        if (session != null) {
            Admin admin = (Admin) session.getAttribute("admin");
            String addUser = (String) session.getAttribute("adduserSession");
            boolean actionIsOk = true;
            // 在此处理 admin 对象
            if (admin != null|| addUser != null) {

                //获取request中的action 来指定应该使用那一部分逻辑
                String action = request.getParameter("action");
                //System.out.printf(action);
//                out.println("<!DOCTYPE html>");
//                out.println("<html>");
//                out.println("<head>");
//                out.println("<title>action</title>");
//                out.println("</head>");
//                out.println("<body>");
//                out.println("<h1>"+action+"</h1>");
//                out.println("</body>");
//                out.println("</html>");
                RequestDispatcher dispatcherToOKjsp = null;
                if (action != null) {
                    switch (action) {
                        case "add_user":
                            Student studentUser = new Student();
                            studentUser.setName(request.getParameter("name"));
                            studentUser.setGender(request.getParameter("gender"));
                            studentUser.setBirthDate(request.getParameter("birth_date"));
                            studentUser.setMajor(request.getParameter("major"));
                            studentUser.setPassword(request.getParameter("password"));
                            // 添加操作
                            AdminDAO.addStudent(studentUser);
                            //在会话中添加一个操作完成信息
                            sessionOk = request.getSession();
                            sessionOk.setAttribute("ok", "增加新用户");

                            dispatcherToOKjsp = request.getRequestDispatcher("ok.jsp");
                            try {
                                dispatcherToOKjsp.forward(request, response);
                            } catch (ServletException | IOException e) {
                                throw new RuntimeException(e);
                            }
                            break;
                        /*学生操作*/
                        case "delete_student":
                            actionIsOk = AdminDAO.deleteStudent(Integer.parseInt(request.getParameter("student_id")));
                            //DatabaseUtil.MakeTheprimaryKeyContiguous();
                            //在会话中添加一个操作完成信息
                            if (actionIsOk) {
                                sessionOk = request.getSession();
                                sessionOk.setAttribute("ok", "删除学生");
                                dispatcherToOKjsp = request.getRequestDispatcher("ok.jsp");
                            }else {
//                                sessionOk = request.getSession();
//                                sessionOk.setAttribute("ok", "notok");
                                notok = "查无此学生,无法删除";
                                sessionNotOk.setAttribute("notok", notok);
                                dispatcherToOKjsp = request.getRequestDispatcher("notok.jsp");
                                actionIsOk = true;
                            }

                            try {
                                dispatcherToOKjsp.forward(request, response);
                            } catch (ServletException | IOException e) {
                                throw new RuntimeException(e);
                            }
                            break;
                        case "search_student":
                            //System.out.println("search_student is ok!!");
                            Student searchstudent =  AdminDAO.getStudentById(Integer.parseInt(request.getParameter("student_id")));
                            if (searchstudent != null) {
                                request.setAttribute("student", searchstudent);
                                RequestDispatcher dispatcherSearchStudent = request.getRequestDispatcher("search_student.jsp");
                                try {
                                    dispatcherSearchStudent.forward(request, response);
                                } catch (ServletException | IOException e) {
                                    throw new RuntimeException(e);
                                }
                            }else{
                                notok = "查无此学生";
                                sessionNotOk.setAttribute("notok", notok);
                                dispatcherToOKjsp = request.getRequestDispatcher("notok.jsp");
                                try {
                                    dispatcherToOKjsp.forward(request, response);
                                } catch (ServletException | IOException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                            break;
                        case "add_student":
                            Student studentA = new Student();
                            studentA.setName(request.getParameter("name"));
                            studentA.setGender(request.getParameter("gender"));
                            studentA.setBirthDate(request.getParameter("birth_date"));
                            studentA.setMajor(request.getParameter("major"));
                            studentA.setPassword(request.getParameter("password"));
                            // 添加操作
                            AdminDAO.addStudent(studentA);

                            //在会话中添加一个操作完成信息
                            sessionOk = request.getSession();
                            sessionOk.setAttribute("ok", "增加学生");

                            dispatcherToOKjsp = request.getRequestDispatcher("ok.jsp");
                            try {
                                dispatcherToOKjsp.forward(request, response);
                            } catch (ServletException | IOException e) {
                                throw new RuntimeException(e);
                            }
                            break;
                        case "update_student":
                            Student studentU = new Student();
                            studentU.setName(request.getParameter("name"));
                            studentU.setGender(request.getParameter("gender"));
                            String birthDateStr = request.getParameter("birth_date");
                            if (birthDateStr != null && !birthDateStr.isEmpty()) {
                                studentU.setBirthDate(String.valueOf(Date.valueOf(birthDateStr))); // 必须是 yyyy-MM-dd 格式
                            }

                            //studentU.setBirthDate(request.getParameter("birth_date"));
                            studentU.setMajor(request.getParameter("major"));
                            studentU.setPassword(request.getParameter("password"));
                            studentU.setStudentId(Integer.parseInt(request.getParameter("student_id")));
                            // 添加操作
                            AdminDAO.updateStudent(studentU);

                            //在会话中添加一个操作完成信息
                            sessionOk = request.getSession();
                            sessionOk.setAttribute("ok", "更新学生信息");
                            dispatcherToOKjsp = request.getRequestDispatcher("ok.jsp");
                            try {
                                dispatcherToOKjsp.forward(request, response);
                            } catch (ServletException | IOException e) {
                                throw new RuntimeException(e);
                            }
                            break;
                        /*课程操作*/
                        case "delete_course"://ok
                            actionIsOk = AdminDAO.deleteCourse(Integer.parseInt(request.getParameter("course_id")));

                            if (actionIsOk) {
                                //在会话中添加一个操作完成信息
                                sessionOk = request.getSession();
                                sessionOk.setAttribute("ok", "删除课程");
                                dispatcherToOKjsp = request.getRequestDispatcher("ok.jsp");
                            }else {
//                                sessionOk = request.getSession();
//                                sessionOk.setAttribute("ok", "notok");
                                notok = "查无此课程,无法删除";
                                sessionNotOk.setAttribute("notok", notok);
                                dispatcherToOKjsp = request.getRequestDispatcher("notok.jsp");
                                actionIsOk = true;
                            }

                            try {
                                dispatcherToOKjsp.forward(request, response);
                            } catch (ServletException | IOException e) {
                                throw new RuntimeException(e);
                            }
                            break;
                        case "search_course":
                            Course searchcourse = AdminDAO.getCourseById(Integer.parseInt(request.getParameter("course_id")));
                            if (searchcourse != null) {
                                request.setAttribute("course", searchcourse);
                                RequestDispatcher dispatcherSearchCourse = request.getRequestDispatcher("search_course.jsp");
                                try {
                                    dispatcherSearchCourse.forward(request,response);
                                } catch (ServletException | IOException e) {
                                    throw new RuntimeException(e);
                                }
                            }else{
                                notok = "查无此课程";
                                sessionNotOk.setAttribute("notok", notok);
                                dispatcherToOKjsp = request.getRequestDispatcher("notok.jsp");
                                try {
                                    dispatcherToOKjsp.forward(request, response);
                                } catch (ServletException | IOException e) {
                                    throw new RuntimeException(e);
                                }
                            }

                            break;
                        case "add_course"://ok
                            Course courseA = new Course();
                            courseA.setCourseId(Integer.parseInt(request.getParameter("course_id"))); // 这是课程号
                            courseA.setCourseName(request.getParameter("course_name"));
                            courseA.setTeacherName(request.getParameter("teacher_name"));
                            courseA.setCredits(Integer.parseInt(request.getParameter("credits"))); // 这是学分
                            AdminDAO.addCourse(courseA);

                            //在会话中添加一个操作完成信息
                            sessionOk = request.getSession();
                            sessionOk.setAttribute("ok", "增加课程");
                            dispatcherToOKjsp = request.getRequestDispatcher("ok.jsp");
                            try {
                                dispatcherToOKjsp.forward(request, response);
                            } catch (ServletException | IOException e) {
                                throw new RuntimeException(e);
                            }
                            break;
                        case "update_course":
                            Course courseU = new Course();
                            courseU.setCourseId(Integer.parseInt(request.getParameter("course_id"))); // 这是课程号
                            courseU.setCourseName(request.getParameter("course_name"));
                            courseU.setTeacherName(request.getParameter("teacher_name"));
                            courseU.setCredits(Integer.parseInt(request.getParameter("credits"))); // 这是学分
                            AdminDAO.updateCourse(courseU);

                            //在会话中添加一个操作完成信息
                            sessionOk = request.getSession();
                            sessionOk.setAttribute("ok", "更新课程");
                            dispatcherToOKjsp = request.getRequestDispatcher("ok.jsp");
                            try {
                                dispatcherToOKjsp.forward(request, response);
                            } catch (ServletException | IOException e) {
                                throw new RuntimeException(e);
                            }
                            break;

                        /*分数操作*/
                        case "delete_score"://ok
                            actionIsOk = AdminDAO.deleteScore(Integer.parseInt(request.getParameter("student_id")),Integer.parseInt(request.getParameter("course_id")));
                            if (actionIsOk) {
                                //在会话中添加一个操作完成信息
                                sessionOk = request.getSession();
                                sessionOk.setAttribute("ok", "删除成绩");
                                dispatcherToOKjsp = request.getRequestDispatcher("ok.jsp");
                            }else {
//                                sessionOk = request.getSession();
//                                sessionOk.setAttribute("ok", "notok");
                                notok = "查无此成绩,无法删除";
                                sessionNotOk.setAttribute("notok", notok);
                                dispatcherToOKjsp = request.getRequestDispatcher("notok.jsp");
                                actionIsOk = true;
                            }

                            try {
                                dispatcherToOKjsp.forward(request, response);
                            } catch (ServletException | IOException e) {
                                throw new RuntimeException(e);
                            }
                            break;
                        case "search_score":
                            Score searchscore =  AdminDAO.getScoreByStudentIdAndCourseId(Integer.parseInt(request.getParameter("student_id")),Integer.parseInt(request.getParameter("course_id")));

                            if (searchscore != null) {
                                request.setAttribute("score", searchscore);
                                // 使用 RequestDispatcher 转发到 JSP 页面
                                RequestDispatcher dispatcherSearchScore = request.getRequestDispatcher("search_score.jsp");
                                try {
                                    dispatcherSearchScore.forward(request, response);
                                } catch (ServletException | IOException e) {
                                    throw new RuntimeException(e);
                                }
                            }else{
                                notok = "查无此成绩";
                                sessionNotOk.setAttribute("notok", notok);
                                dispatcherToOKjsp = request.getRequestDispatcher("notok.jsp");
                                try {
                                    dispatcherToOKjsp.forward(request, response);
                                } catch (ServletException | IOException e) {
                                    throw new RuntimeException(e);
                                }
                            }

                            break;
                        case "add_score":
                            Score scoreA = new Score();
                            scoreA.setStudentId(Integer.parseInt(request.getParameter("student_id")));
                            scoreA.setCourseId(Integer.parseInt(request.getParameter("course_id")));
                            scoreA.setScore(Double.parseDouble(request.getParameter("score")));
                            String examDateStrA = request.getParameter("exam_date");
                            if (examDateStrA != null && !examDateStrA.isEmpty()) {
                                scoreA.setExamDate(String.valueOf(Date.valueOf(examDateStrA)));
                            }
                            //scoreA.setStudentName(request.getParameter("exam_date"));

                            System.out.printf(scoreA.string());

                            AdminDAO.addScore(scoreA);

                            //在会话中添加一个操作完成信息
                            sessionOk = request.getSession();
                            sessionOk.setAttribute("ok", "增加成绩");
                            dispatcherToOKjsp = request.getRequestDispatcher("ok.jsp");
                            try {
                                dispatcherToOKjsp.forward(request, response);
                            } catch (ServletException | IOException e) {
                                throw new RuntimeException(e);
                            }
                            break;
                        case "update_score":
                            Score scoreU = new Score();
                            scoreU.setStudentId(Integer.parseInt(request.getParameter("student_id")));
                            scoreU.setCourseId(Integer.parseInt(request.getParameter("course_id")));
                            String examDateStr = request.getParameter("exam_date");
                            if (examDateStr != null && !examDateStr.isEmpty()) {
                                scoreU.setExamDate(String.valueOf(Date.valueOf(examDateStr)));
                            }
                            scoreU.setStudentName(request.getParameter("exam_date"));
                            scoreU.setScore(Double.parseDouble(request.getParameter("score")));
                            AdminDAO.updateScore(scoreU);

                            //在会话中添加一个操作完成信息
                            sessionOk = request.getSession();
                            sessionOk.setAttribute("ok", "更新成绩");
                            dispatcherToOKjsp = request.getRequestDispatcher("ok.jsp");
                            try {
                                dispatcherToOKjsp.forward(request, response);
                            } catch (ServletException | IOException e) {
                                throw new RuntimeException(e);
                            }
                            break;
                        default:

                            break;
                    }
                }
                else{
                    // 使用 RequestDispatcher 转发到 JSP 页面
                    RequestDispatcher dispatcher = request.getRequestDispatcher("admin_home.jsp");
                    try {
                        dispatcher.forward(request, response);
                    } catch (ServletException e) {
                        throw new RuntimeException(e);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
            else {
                // 没有登录的情况，重定向到登录页面
                // 没有登录的情况，重定向到登录页面
                RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
                try {
                    dispatcher.forward(request, response);
                } catch (ServletException | IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        else {
            // 没有登录的情况，重定向到登录页面
            // 没有登录的情况，重定向到登录页面
            RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
            try {
                dispatcher.forward(request, response);
            } catch (ServletException | IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型
        response.setContentType("text/html;charset=UTF-8");
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        doGet(request, response);
    }
}
